package com.yunqian.config;

import com.yunqian.redot.service.CoursesOrderService;
import com.yunqian.redot.service.TicketOrderService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * @author czy
 * @describe
 * @date 2018/7/17
 */
@WebListener
@Log4j2
public class StartApplicationListener implements ServletContextListener {

    @Autowired
    private CoursesOrderService coursesOrderService;
    @Autowired
    private TicketOrderService ticketOrderService;

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        log.info("------项目启动，开始执行监听器------");
        new Thread(new TokenThread()).start();
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }

    class TokenThread implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    // 更新报名订单
                    coursesOrderService.updateOrderStatus();
                    // 更新购票订单
                    ticketOrderService.updateOrderStatus();
                    // 休眠60秒
                    Thread.sleep(60 * 1000);
                } catch (InterruptedException e) {
                    try {
                        Thread.sleep(60 * 1000);
                    } catch (InterruptedException e1) {
                        log.error("{}", e1);
                    }
                    log.error("{}", e);
                }
            }
        }
    }
}
